<?php


namespace common\helpers\Uploads;


use common\helpers\commonApi;

class TxCosApi implements Upload
{
    private $cosClient = null;
    private $secretId = null;
    private $secretKey = null;
    private $region = null;
    private $bucket = null;
    private $host = null;

    public function __construct($secretId, $secretKey, $region, $bucket, $host = '')
    {
        $this->secretId = $secretId; //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $this->secretKey = $secretKey; //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $this->region = $region; //替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $this->bucket = $bucket; //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
        $this->host = $host;

        if (!$this->cosClient) {
            $config = [
                'region' => $this->region,
                'schema' => 'http', //协议头部，默认为http
                'credentials' => [
                    'secretId' => $this->secretId,
                    'secretKey' => $this->secretKey
                ]
            ];
            $this->cosClient = new \Qcloud\Cos\Client($config);
        }
    }

    public function uploadFile(string $filePath, string $fileName)
    {
        $this->cosClient->putObject([
            'Bucket' => $this->bucket, //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
            'Key' => $filePath,
            'Body' => $fileName
        ]);
        return commonApi::message();
    }

    public function delete(string $filePath)
    {
        $this->cosClient->deleteObject([
            'Bucket' => $this->bucket, //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
            'Key' => $filePath
        ]);
        return commonApi::message();
    }

    public function deleteAll(array $filePaths)
    {
        $success = 0;
        $fail = 0;
        $fail_data = [];
        $success_data = [];
        foreach ($filePaths as $filePath){
            $res = $this->delete($filePath);
            if ($res['success']){
                $success += 1;
                $success_data[] = $filePath;
            }else{
                $fail += 1;
                $fail_data[] = $filePath;
            }
        }
        return commonApi::message("删除失败：成功{$success}条，失败{$fail}条", true, ['success' => $success_data, 'fail' => $success_data]);
    }
}